package org.example.sdpback.service.impl;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.example.sdpback.domain.entity.Iteration;
import org.example.sdpback.domain.entity.Task;
import org.example.sdpback.domain.entity.User;
import org.example.sdpback.domain.vo.IterationVO;
import org.example.sdpback.domain.vo.TaskVO;
import org.example.sdpback.mapper.TaskMapper;
import org.example.sdpback.service.ITaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.sdpback.service.IterationService;
import org.example.sdpback.service.UserService;
import org.example.sdpback.utils.ThreadLocalUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zxy
 * @since 2024-12-06
 */
@Service
@RequiredArgsConstructor
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    private final UserService userService;
    private final IterationService iterationService;

    @Override
    public void saveTask(Task task) {
        User user = ThreadLocalUtil.get();
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        task.setCreateUserId(user.getId());
        this.save(task);
    }

    @Override
    public List<TaskVO> taskList() {

        List<Task> list = this.list();
        List<TaskVO> taskVOS = new ArrayList<>();

        if (list == null || list.size() == 0){
            return null;
        }

        // 获取对应创建人id，执行人id，迭代id集合
        List<Long> createUserIds = list.stream().map(Task::getCreateUserId).collect(Collectors.toList());
        List<String> executeUserIds = list.stream().map(Task::getExecuteUserId).collect(Collectors.toList());
        List<Long> iterationIds = list.stream().map(Task::getIterationId).collect(Collectors.toList());

        // 处理执行人ID集合，去重
        Set<String> set = new HashSet<>();
        for (String executeUserId : executeUserIds){
            List<String> resultList = Arrays.asList(executeUserId.split(","));
            set.addAll(resultList);
        }
        executeUserIds = new ArrayList<>(set);

        // 获取用户信息, 迭代信息
        Map<Long, User> createUsers = userService.listByIds(createUserIds).stream().collect(Collectors.toMap(User::getId, Function.identity()));
        Map<Long, User> executeUsers = userService.listByIds(executeUserIds).stream().collect(Collectors.toMap(User::getId, Function.identity()));
        Map<Long, Iteration> iterations = iterationService.listByIds(iterationIds).stream().collect(Collectors.toMap(Iteration::getId, Function.identity()));

        // 封装返回结果
        list.forEach(task -> {
            TaskVO taskVO = new TaskVO();
            BeanUtil.copyProperties(task, taskVO);
            taskVO.setCreateUser(createUsers.get(task.getCreateUserId()).getUsername());

            ArrayList<String> excuteUerNames = new ArrayList<>();

            Arrays.stream(task.getExecuteUserId().split(",")).map(Long::parseLong).forEach(executeUserId -> {
                excuteUerNames.add(executeUsers.get(executeUserId).getUsername());
            });
            taskVO.setExecuteUser(excuteUerNames);
            taskVO.setIterationName(iterations.get(task.getIterationId()).getName());
            taskVO.setType(task.getType().getName());
            taskVO.setStatus(task.getStatus().getName());
            taskVOS.add(taskVO);
        });

        return taskVOS;
    }
}
